package com.zhou.JavaAndroidFirm.activity;

import android.app.Activity;
import android.app.ActivityOptions;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.ActivityOptionsCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions;
import com.bumptech.glide.request.RequestOptions;
import com.zhou.JavaAndroidFirm.R;
import com.zhou.JavaAndroidFirm.app.AppConstant;
import com.zhou.JavaAndroidFirm.base.BaseActivity;
import com.zhou.JavaAndroidFirm.bean.NewsDetail;
import com.zhou.JavaAndroidFirm.constract.NewsDetailContract;
import com.zhou.JavaAndroidFirm.model.NewsDetailModel;
import com.zhou.JavaAndroidFirm.presenter.NewsDetailPresenter;
import com.zhou.JavaAndroidFirm.rx.RxSchedulers;
import com.zhou.JavaAndroidFirm.utils.TimeUtil;
import com.zhou.JavaAndroidFirm.widget.RichText;

import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import rx.Observable;
import rx.Subscriber;

import static com.zhou.JavaAndroidFirm.app.AppConstant.NEWS_IMG_RES;

/**
 * @author Administrator
 * @date 2018/7/17 0017
 * @des
 */
public class NewsDetailActivity extends BaseActivity<NewsDetailPresenter, NewsDetailModel> implements NewsDetailContract.View {
    @BindView(R.id.news_detail_photo_iv)
    ImageView newsDetailPhotoIv;
    @BindView(R.id.mask_view)
    View maskView;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.toolbar_layout)
    CollapsingToolbarLayout toolbarLayout;
    @BindView(R.id.app_bar)
    AppBarLayout appBar;
    @BindView(R.id.news_detail_from_tv)
    TextView newsDetailFromTv;
    @BindView(R.id.news_detail_body_tv)
    RichText newsDetailBodyTv;
    @BindView(R.id.progress_bar)
    ProgressBar progressBar;
    @BindView(R.id.fab)
    FloatingActionButton fab;
    private String postId;
    //    private URLImageGetter mUrlImageGetter;
    private String mNewsTitle;
    private String mShareLink;

    public static void startAction(Context mContext, View view, String postId, String imgUrl) {
        Intent intent = new Intent(mContext, NewsDetailActivity.class);
        intent.putExtra(AppConstant.NEWS_POST_ID, postId);
        intent.putExtra(NEWS_IMG_RES, imgUrl);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            ActivityOptions options = ActivityOptions
                    .makeSceneTransitionAnimation((Activity) mContext, view, AppConstant.TRANSITION_ANIMATION_NEWS_PHOTOS);
            mContext.startActivity(intent, options.toBundle());
        } else {
            //让新的Activity从一个小的范围扩大到全屏
            ActivityOptionsCompat options = ActivityOptionsCompat
                    .makeScaleUpAnimation(view, view.getWidth() / 2, view.getHeight() / 2, 0, 0);
            ActivityCompat.startActivity((Activity) mContext, intent, options.toBundle());
        }
    }

    @Override
    protected int getLayoutId() {
        return R.layout.act_news_detail;
    }

    @Override
    protected void initPresenter() {
        mPresenter.onCreate(mModel, this);

    }

    @Override
    protected void initView(Bundle bundle) {
        SetTranslanteBar();
        postId = getIntent().getStringExtra(AppConstant.NEWS_POST_ID);
        mPresenter.getOneNewsData(postId);
    }

    private boolean canBrowse(Intent intent) {
        return intent.resolveActivity(getPackageManager()) != null && mShareLink != null;
    }

    @Override
    protected void initEvent() {
        toolbar.inflateMenu(R.menu.news_detail);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    finishAfterTransition();
                } else {
                    finish();
                }
            }
        });
        toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                if (item.getItemId() == R.id.action_web_view) {
                    NewsBrowserActivity.startAction(NewsDetailActivity.this, mShareLink, mNewsTitle);
                } else {
                    Intent intent = new Intent();
                    intent.setAction("android.intent.action.VIEW");
                    if (canBrowse(intent)) {
                        Uri uri = Uri.parse(mShareLink);
                        intent.setData(uri);
                        startActivity(intent);
                    }
                }
                return true;
            }
        });


        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mShareLink == null) {
                    mShareLink = "";
                }

                Intent intent = new Intent(Intent.ACTION_SEND);
                intent.setType("text/plain");
                intent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.share));
                intent.putExtra(Intent.EXTRA_TEXT, getString(R.string.share_contents, mNewsTitle, mShareLink));
                startActivity(Intent.createChooser(intent, getTitle()));
            }
        });

        newsDetailBodyTv.setOnImageClickListener(new RichText.OnImageClickListener() {
            @Override
            public void imageClicked(List<String> imageUrls, int position) {
                // 查看大图
                BigImagePagerActivity.startImagePagerActivity(mContext, imageUrls, position);
            }
        });
    }

    @Override
    public void returnOneNewsData(NewsDetail newsDetail) {
        mShareLink = newsDetail.getShareLink();
        mNewsTitle = newsDetail.getTitle();
        String newsSource = newsDetail.getSource();
        String newsTime = TimeUtil.formatDate(newsDetail.getPtime());
        final String newsBody = newsDetail.getBody();
        String NewsImgSrc = getImgSrcs(newsDetail);

        setToolBarLayout(mNewsTitle);

        newsDetailFromTv.setText(getString(R.string.news_form, newsSource, newsTime));
        setNewsDetailPhotoIv(NewsImgSrc);


        Observable.timer(500, TimeUnit.MILLISECONDS)
                .compose(RxSchedulers.<Long>io_main())
                .subscribe(new Subscriber<Long>() {
                    @Override
                    public void onCompleted() {
                        progressBar.setVisibility(View.GONE);
                        fab.setVisibility(View.VISIBLE);
                    }

                    @Override
                    public void onError(Throwable e) {
                        progressBar.setVisibility(View.GONE);
                    }

                    @Override
                    public void onNext(Long aLong) {
                        newsDetailBodyTv.setRichText(newsBody);
                    }
                });
    }

    private void setNewsDetailPhotoIv(String newsImgSrc) {
        Glide.with(mContext)
                .load(newsImgSrc)
                .apply(new RequestOptions()
                        .fitCenter()
                        .error(R.drawable.ic_empty_picture)
                )
                .transition(DrawableTransitionOptions.withCrossFade())
                .into(newsDetailPhotoIv);
    }

    private void setToolBarLayout(String mNewsTitle) {
        toolbarLayout.setTitle(mNewsTitle);
        toolbarLayout.setExpandedTitleColor(ContextCompat.getColor(this, R.color.white));
        toolbarLayout.setCollapsedTitleTextColor(ContextCompat.getColor(this, R.color.primary_text_white));

    }

    private String getImgSrcs(NewsDetail newsDetail) {
        List<NewsDetail.ImgBean> imgSrcs = newsDetail.getImg();
        String img;
        if (imgSrcs != null && imgSrcs.size() > 0) {
            img = imgSrcs.get(0).getSrc();
        } else {
            img = getIntent().getStringExtra(NEWS_IMG_RES);
        }
        return img;

    }

    @Override
    public void showTip(String tip) {

    }
}
